﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.Utils
{
    public class ReqParameterUtil
    {
        /// <summary>
        /// 获取根据参数类型赋值后转换的Url参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">类型</param>
        /// <param name="outparas">不转换的字段</param>
        /// <returns></returns>
        public static string GetUrlParam<T>(T model,params string[] outparas)
        {
            var sdic = GetResultDictionary(model);
            var dic = FilterPara(sdic, outparas);
            return dic.Count > 0 ? $"?{CreateLinkString(dic)}" : string.Empty;
        }
        /// <summary>
        /// 获取根据参数类型赋值后转换的Json数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">类型</param>
        /// <param name="outparas">不转换的字段名称</param>
        /// <returns></returns>
        public static string GetJsonParam<T>(T model, params string[] outparas)
        {
            var sdic = GetResultDictionary(model);
            var dic = FilterPara(sdic, outparas);
            return JsonConvert.SerializeObject(dic);
        }

        private static Dictionary<string, string> FilterPara(SortedDictionary<string, string> dicArrayPre,
            params string[] paras)

        {
            return dicArrayPre.Where(temp => !paras.Contains(temp.Key) && !string.IsNullOrEmpty(temp.Value)).ToDictionary(temp => temp.Key, temp => temp.Value);
        }

        private static SortedDictionary<string, string> GetResultDictionary<T>(T model)

        {
            var sArray = new SortedDictionary<string, string>();
            // 把实体类中的属性名称转换成List<string>
            var modelDict = model.GetType().GetProperties().ToDictionary(a => a.Name);
            var paramList = modelDict.Select(dkey => dkey.Key).ToList();
            foreach (var p in paramList)
            {
                if (!modelDict.TryGetValue(p, out var pi)) continue;
                var obj = pi.GetValue(model, null);
                if (obj != null)
                    sArray.Add(p, obj.ToString());
            }
            return sArray;
        }

        private static string CreateLinkString(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
                prestr.Append($"{temp.Key}={temp.Value}&"); //temp.Key + "=" + temp.Value + "&");
            return prestr.ToString().TrimEnd('&');
        }
    }
}
